/*
 * 文件名：BeforeToolController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月30日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.mgr.bpa.service.InnerAgrtService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.BeforeToolAssist;
import top.infopub.mgr.ic.domain.BeforeToolDomain;
import top.infopub.mgr.ic.service.BeforeToolService;
import top.infopub.mgr.ic.vo.BeforeToolVo;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.ic.BeforeToolAtt;
import top.infopub.model.ic.BeforeToolDetail;
import top.infopub.model.mkt.DisclosePro;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 开工前管理工具审批
 * @author WuZhiyang
 * @version 2020年3月30日
 * @see BeforeToolController
 * @since
 */
@Controller
@RequestMapping("/beforeTool")
public class BeforeToolController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private BeforeToolService beforeToolService;

    @Autowired
    private InnerAgrtService innerAgrtService;

    /**
     * 开工前管理工具审批列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-beforeTool-list";
    }

    /**
     * 开工前管理工具审批列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<BeforeToolDomain> queryDataByCondition(BeforeToolVo beforeToolVo,
                                                        ParamPage paramPage) {
        Page<BeforeToolDomain> page = new Page<BeforeToolDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (beforeToolVo.getEndDate() != null) {
            beforeToolVo.setEndDate(DateUtils.addDays(beforeToolVo.getEndDate(), 1));
        }
        page = beforeToolService.selectByDomainWhere(page, beforeToolVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 开工前管理工具审批-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<BeforeToolDomain> queryMyCheckDataByCondition(BeforeToolVo beforeToolVo,
                                                               ParamPage paramPage) {
        Page<BeforeToolDomain> page = new Page<BeforeToolDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (beforeToolVo.getEndDate() != null) {
            beforeToolVo.setEndDate(DateUtils.addDays(beforeToolVo.getEndDate(), 1));
        }
        beforeToolVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = beforeToolService.selectMyCheckByDomainWhere(page, beforeToolVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 开工前管理工具审批-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询交底的记录
        DisclosePro disclosePro = new DisclosePro();
        disclosePro.setProcessStatus("9");
        List<DisclosePro> disclosePros = discloseProService.selectByEntityWhere(disclosePro);
        request.setAttribute("disclosePros", disclosePros);
        return "ic/lay-beforeTool-add";
    }

    /**
     * 根据id查询开工前管理工具审批详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 开工前管理工具审批Id
     * @return
     * @see
     */
//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        BeforeToolVo beforeToolVo = beforeToolService.queryById(id);
//        Map<String, Object> whereMap = Maps.newHashMap();
//        whereMap.put("proCode", beforeToolVo.getProCode());
//        whereMap.put("processStatus", "9");
//        whereMap.put("orderCondition", "ADD_TIME desc");
//        List<InnerAgrt> innerAgrts = innerAgrtService.selectByMapWhere(whereMap);
//        if(innerAgrts != null && innerAgrts.size() > 0){
//            InnerAgrt innerAgrt = innerAgrts.get(0);
//            if(innerAgrt != null){
//                InnerAgrtDomain innerAgrtDomain = innerAgrtService.selectByIds(innerAgrt.getId());
//                beforeToolVo.setSgCoopName(innerAgrtDomain.getSgCoopName());
//            }
//        }
//        request.setAttribute("modelDetail", beforeToolVo);
//        map.put("beforeToolVo", beforeToolVo);
//        // 审批flag
//        request.setAttribute("processDealWith", processDealWith);
//        // 审批data
//        processData(request, beforeToolVo.getProcessId());
//        return new ModelAndView("ic/lay-beforeTool-detail", map);
//    }

    /**
     * 新增开工前管理工具审批
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(BeforeToolAssist beforeToolAssist) {

        //开工前管理工具审批表处理
        beforeToolAssist.setHrDeptId(beforeToolAssist.getHrDeptid());
        beforeToolAssist.setHrOrgId(beforeToolAssist.getHrOrgid());
        beforeToolAssist.setStaffName(beforeToolAssist.getStaffname());
        beforeToolAssist.setHrStaffApplyId(beforeToolAssist.getHrStaffApplyid());
        String proCodeAndCodes = beforeToolAssist.getProCodeAndCodes();
        String[] split = proCodeAndCodes.split("\\_");
        beforeToolAssist.setProCode(split[0]);
        beforeToolAssist.setProName(split[2]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        beforeToolAssist.setId(id);
        beforeToolAssist.setAddBy(vo.getId());
        beforeToolAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("ic_before_tool");
        beforeToolAssist.setCodes(code);
        // 处理processId
        beforeToolAssist.setProcessId(IdFactory.getUUIDUpper());
        beforeToolAssist.setProcessStatus("1");//审批中
        beforeToolAssist.setUptBy(vo.getId());
        beforeToolAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //明细表
        List<BeforeToolDetail> beforeToolDetails = new ArrayList<BeforeToolDetail>();
        //上传附件
        List<BeforeToolAtt> beforeToolAtts = new ArrayList<BeforeToolAtt>();
        String[] showIdxDetail = beforeToolAssist.getShowIdxDetail();
        if (showIdxDetail != null && showIdxDetail.length > 0) {
            for (int i = 0; i < showIdxDetail.length; i++ ) {
                String showIdx = showIdxDetail[i];
                String itemName = beforeToolAssist.getItemNameDetail()[i];
                String itemMemo = beforeToolAssist.getItemMemoDetail()[i];
                BeforeToolDetail beforeToolDetail = new BeforeToolDetail();
                String beforeToolDetailId = IdFactory.getUUIDUpper();
                beforeToolDetail.setToolId(id);
                beforeToolDetail.setId(beforeToolDetailId);
                beforeToolDetail.setShowIdx(Integer.parseInt(showIdx));
                beforeToolDetail.setItemName(itemName);
                beforeToolDetail.setItemMemo(itemMemo);
                beforeToolDetail.setAddBy(vo.getId());
                beforeToolDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                beforeToolDetails.add(beforeToolDetail);
            }

            String[] fileAtts1 = beforeToolAssist.getFileAtts1();
            String[] showIdxAtt = beforeToolAssist.getShowIdxAtt();
            if (fileAtts1 != null) {
                for (int i = 0; i < fileAtts1.length; i++ ) {
                    BeforeToolAtt beforeToolAtt = createFileAtt(vo, id, fileAtts1[i]);
                    String showIdx = showIdxAtt[i];
                    beforeToolAtt.setDetailId(showIdx);
                    beforeToolAtts.add(beforeToolAtt);
                }
            }

            for (BeforeToolAtt beforeToolAtt : beforeToolAtts) {
                for (BeforeToolDetail beforeToolDetail : beforeToolDetails) {
                    if (beforeToolAtt.getDetailId().equals(
                        String.valueOf(beforeToolDetail.getShowIdx()))) {
                        beforeToolAtt.setDetailId(beforeToolDetail.getId());
                        break;
                    }
                }
            }

        }
        beforeToolService.saveBeforeTool(beforeToolAssist, beforeToolDetails, beforeToolAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "投建管理 -开工前管理工具审批：项目名="
                                                              + beforeToolAssist.getProName(),
            null);
        return RspVo.getSuccessResponse();
    }

    private BeforeToolAtt createFileAtt(AuthorizationVO vo, String toolId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        BeforeToolAtt fileAtt = new BeforeToolAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setToolId(toolId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "beforeToolAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
    
    /**
     * 根据id查询交底记录
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getBeforeToolById")
//    @ResponseBody
//    public Map<String, Object> getBeforeToolById(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        try {
//            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//            String[] split = proCodeAndCodes.split("\\_");
//            DiscloseProVo discloseProVo = discloseProService.selectById(split[1]);
//            Map<String, Object> whereMap = Maps.newHashMap();
//            whereMap.put("proCode", discloseProVo.getProCode());
//            whereMap.put("processStatus", "9");
//            whereMap.put("orderCondition", "ADD_TIME desc");
//            List<InnerAgrt> innerAgrtList = innerAgrtService.selectByMapWhere(whereMap);
//            if(innerAgrtList != null && innerAgrtList.size() > 0){
//                InnerAgrt innerAgrt = innerAgrtList.get(0);
//                if(innerAgrt != null){
//                    InnerAgrtDomain innerAgrtDomain = innerAgrtService.selectByIds(innerAgrt.getId());
//                    discloseProVo.setSgCoopName(innerAgrtDomain.getSgCoopName());
//                    discloseProVo.setSgCoopId(innerAgrtDomain.getSgCoopId());
//                }
//            }
//            map.put("discloseProVo", discloseProVo);
//        }
//        catch (Exception e) {
//            log.error("查询交底记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

}